/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.edu.kamai.xmlparser;

import java.io.File;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.DOMOutputter;
import org.jdom.output.XMLOutputter;


/**
 *
 * @author xyzhu
 */
public class testWithJDom {
    XMLOutputter printer = null;
    
    public testWithJDom(){
        printer = new XMLOutputter();
    }
    
    /**
     * Parsing an XML file and then
     * playing with some basic JDOM functionality!
     * @param anXmlDocFile
     */
    public void parseAndPlay(File anXmlDocFile){
        SAXBuilder parser = new SAXBuilder();
        try {
            //get the dom-document
            Document doc = parser.build(anXmlDocFile);
            // illustrate some jdom tree walk and print sample
            System.out.println(doc.getRootElement().getName());
            Element firstChild = (Element)doc.getRootElement().getChildren().get(0);
            System.out.println(">> "+firstChild.getName()+":"+ firstChild.getAttribute("type").getValue());
            System.out.println(">>>>" +firstChild.getText());
            
            //easily print
            this.printJDom(doc);
            
            // do you want an classic DOM? no prob!
            DOMOutputter out = new DOMOutputter();
            org.w3c.dom.Document domDoc= out.output(doc);
            System.out.println(domDoc.getImplementation().toString());
            
            //lets print in the console the JDomTree
            this.printJDom(doc);

            //lets make some changes!
            Element child =(Element) doc.getRootElement().getChildren().get(0);
            child.setName("NewNAME");
            child.setText("Water Mellon");

            //lets print in the console the altered JDomTree
            this.printJDom(doc);
            
            
        }catch (JDOMException ex) {
            ex.printStackTrace();
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Using the XMLOuputer prints in the Console
     * the JDOM tree!
     * @param aJDOMdoc A JDOM Document
     * @throws java.io.IOException
     */
    public void printJDom(Document aJDOMdoc) throws IOException{
        System.out.println("<------------XML DOCUMENT------------>");
        this.printer.output(aJDOMdoc, System.out);
    }
    
    
    
    public static void main(String[] args){
        testWithJDom test = new testWithJDom();
        String curDir = System.getProperty("user.dir");
        System.out.println(curDir);
        test.parseAndPlay(new File("test.xml"));
    } 
}
